<template src="./template.html"></template>

<script>
/* global _ */
import ResizeMixin from 'mixins/resize'
import { FILE_MIME_TYPE } from 'common/consts';
import { tplToDownload } from 'common/common-models'
import { COL_INDEXS } from './consts';
import { importCourseCheckExcel, importCourseSaveExcel } from '../models';

export default {
  mixins: [ResizeMixin],
  data() {
    return {
      fileMimeType: FILE_MIME_TYPE, // 文件上传类型
      COL_INDEXS,
      isPageLoading: false,

      tableList: [],

      file: null,
      checkType: '', // fail--审核失败；succ--审核成功
      failNum: 0
    };
  },
  computed: {
    courseId() {
      return this.$route.params.courseId
    }
  },

  methods: {
    async $handleCheckExcel(file, fileList) {
      const fileType = file.raw.type
      if (this.fileMimeType[4].indexOf(fileType) === -1) {
        this.$message.warning('只支持上传excel文件')
        const tempFileIdx = fileList.findIndex(it => it.uid === file.uid)
        fileList.splice(tempFileIdx, 1)
        return
      }
      this.isLoading = true
      const params = {
        courseId: this.courseId,
        file: file
      }
      try {
        const res = await importCourseCheckExcel(params)
        this.tableList = res.data || []
        let isFail = false
        let failNum = 0
        this.tableList.forEach(it => {
          if (it.message.indexOf('检验通过') <= -1) {
            isFail = true
            failNum += 1
          }
        });
        if (isFail) {
          this.checkType = 'fail'
          this.failNum = failNum
        } else {
          this.checkType = 'succ'
          this.failNum = 0
        }
        this.file = file
        this.isLoading = false
      } catch (err) {
        this.isLoading = false
        console.log(err)
        this.$message.error(err.message || '操作异常')
      }
    },
    $debounceSave() {
      if (!this.debounceSave) {
        this.debounceSave = _.debounce(this.$handleSave, 500)
      }
      this.debounceSave()
    },
    async $handleSave() {
      this.isLoading = true
      const params = {
        courseId: this.courseId,
        file: this.file
      }
      try {
        await importCourseSaveExcel(params)
        this.$message.success('学员信息已导入成功！')
        this.isLoading = false
        this.$router.go(-1)
      } catch (err) {
        this.isLoading = false
        console.log(err)
        this.$message.error(err.message || '拉取列表异常')
      }
    },
    $cancelImport() {
      this.checkType = ''
      this.tableList = []
      this.file = ''
      this.failNum = 0
    },
    async $downTraineeTem() {
      tplToDownload('2')
    }
  },
  created() {
  },
};
</script>
